import key from "keymaster";
import { query as query1 } from "../services/example";
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export default {
  namespace: "products",
  state: {
    count: 0,
    lists: [],
  },
  // 同步更新的方法
  reducers: {
    delete(state, { id }) {
      return {
        ...state,
        lists: state.lists.filter((item) => item.id !== id),
      };
    },
    addCount(state) {
      return { ...state, count: state.count + 1 };
    },
    minusCount(state) {
      return { ...state, count: state.count - 1 };
    },
    addList(state, { item }) {
      return { ...state, lists: [...state.lists, ...item] };
    },
  },

  effects: {
    // *addCountAsync(action, effects) {
    //   const { put, select, call } = effects;
    //   const data = yield select();
    //   console.log("我被点击了");
    //   yield call(delay, 2000);
    //   yield put({ type: "addCount" });
    // },

    // 设置不同类型的监听器，监听器类型有takeLatest, takeEvery, throttle, debounce
    addCountAsync: [
      function* (action, effects) {
        const { put, call } = effects;
        yield call(delay, 2000);
        yield put({ type: "addCount" });
      },
      {
        type: "takeLatest",
      },
    ],
    *minusCountAsync(action, effects) {
      const { put, call } = effects;
      yield call(delay, 2000);
      yield put({ type: "minusCount" });
    },
    *query(action, effects) {
      const { put, call } = effects;
      const data = yield call(query1);
      yield call(delay, 2000);
      yield put({
        type: "addList",
        item: [
          { name: "dva", id: 1 },
          { name: "antd", id: 2 },
        ],
      });
      console.log("查询数据", data);
    },
  },
  subscriptions: {
    async init(params) {
      const { dispatch, history } = params;
      // await delay(2000);
      // dispatch({ type: "addCount" });
      // 返回一个函数，用于在组件卸载时取消监听
      const unListen = history.listen(async (location) => {
        if (location.pathname === "/product") {
          dispatch({ type: "query" });
          //  移除监听
          unListen && unListen();
        }
        console.log("监听被执行了", location);
      });
    },
    // setup(params) {
    //   console.log("订阅被执行了", params);
    // },
    keyEvent({ dispatch }) {
      key("⌘+up, ctrl+up", () => {
        dispatch({ type: "addCount" });
      });

      key("⌘+down, ctrl+down", () => {
        dispatch({ type: "minusCount" });
      });
    },
  },
};
